//
//  TF_tool.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/4/8.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import Foundation
import UIKit
extension UIColor {
    static func randomColor(alpha:CGFloat? = nil)-> UIColor {
        let red = CGFloat.random(in: 0...1)
        let green = CGFloat.random(in: 0...1)
        let blue = CGFloat.random(in: 0...1)
        var newAlpha:CGFloat = 1
        if(alpha != nil)
        {
            newAlpha = alpha!
        }
        return UIColor(red: red, green: green, blue: blue, alpha: newAlpha)
    }
    
    convenience init(hexString: String) {
        let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        
        if hexString.hasPrefix("#") {
            scanner.scanLocation = 1
        }
        
        var color: UInt32 = 0
        scanner.scanHexInt32(&color)
        
        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        
        self.init(red: red, green: green, blue: blue, alpha: 1)
    }
    
    // UIColor -> Hex String
    var hexString: String? {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        
        let multiplier = CGFloat(255.999999)
        
        guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else {
            return nil
        }
        
        if alpha == 1.0 {
            return String(
                format: "#%02lX%02lX%02lX",
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier)
            )
        }
        else {
            return String(
                format: "#%02lX%02lX%02lX%02lX",
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier),
                Int(alpha * multiplier)
            )
        }
    }
    
    
        
}
//扩展
extension NSObject {
    func currentTextView(_ textView:UIView)->Bool
    {
        if let view = UIResponder.tf_firstResponder() {
            
            if (view is UITextView){

                let firstResponder = view as! UITextView
                
                //不是聊天不用处理
                if (firstResponder == textView) {
                    return true
                }
            }else if (view is UITextField){
                
                let firstResponder = view as! UITextField
                
                //不是聊天不用处理
                if (firstResponder == textView) {
                    return true
                }
            }
            
        }
        return false
    }
    var TF_className: String {
        return NSStringFromClass(type(of: self))
    }
    /// iPhoneX、iPhoneXR、iPhoneXs、iPhoneXs Max等
      /// 判断刘海屏，返回true表示是刘海屏
      ///
      var isNotchScreen: Bool {
      
          
          if UIDevice.current.userInterfaceIdiom == .pad {
      
              return false
          }
          
          let size = UIScreen.main.bounds.size
          let notchValue: Int = Int(size.width/size.height * 100)
          
          if 216 == notchValue || 46 == notchValue {
      
              
              return true
          }
          
          return false
      }
    
    
    func TF_toast(_ msg:String)
    {

        TalkfunSharedTools.keyWindow().toast(msg, position: CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/2))
    }
  

}
extension CATextLayer {
    
    @objc static func TF_watermark(text:String,font:UIFont,point:CGPoint)-> CATextLayer
    {
        
        let textLayer = CATextLayer()
        
        let myString = "计算高度专用"
        let attrsSize: CGSize = myString.size(withAttributes: [NSAttributedString.Key.font: font])
        

        var  hh:CGFloat = 0
        
        if (font.pointSize<=20) {
            hh = 5
        }
        
        textLayer.frame = CGRect(x: point.x, y: point.y, width: attrsSize.width, height: attrsSize.height+hh)
       
        textLayer.backgroundColor = UIColor.clear.cgColor
        
        // 设置文字属性
        textLayer.foregroundColor = UIColor(red: 246/255.0, green: 246/255.0, blue: 246/255.0, alpha: 1).cgColor
        textLayer.alignmentMode = CATextLayerAlignmentMode.left
        textLayer.isWrapped = false
        
      
        let fontRef = CGFont.init(font.fontName as CFString)
                textLayer.font = fontRef
                textLayer.fontSize = font.pointSize

        
        // 选择文本
        textLayer.string = text
        
        textLayer.contentsScale = UIScreen.main.scale
        textLayer.shadowOpacity = 0.8
        
        
        textLayer.shadowOffset = CGSize(width: 0, height: 1)
        textLayer.shadowRadius = 3.0
        
        return textLayer;
    }

}

extension UIFont {
    @objc static func PingFang(size:CGFloat)-> UIFont
    {
      var font = UIFont.init(name: "PingFang SC", size: size)
        if font == nil {
            font = UIFont.systemFont(ofSize: size)
        }
        
        return font!
    }
    @objc static func nameFang(_ name:String , size:CGFloat)-> UIFont
    {
      var font = UIFont(name: name, size: size)
        if font == nil {
            font = UIFont.systemFont(ofSize: size)
        }
        
        return font!
    }
    
}

extension UIView {
    func tf_roundedCorners(rect: CGRect?=nil,corners: UIRectCorner,cornerRadii: CGSize)
     {
         
         self.layer.mask = nil
         var newRect = self.bounds
         if(rect != nil)
         {
             newRect = rect!
         }
       
         let maskPath_2 = UIBezierPath.init(roundedRect: newRect, byRoundingCorners: corners, cornerRadii: cornerRadii)
          
         let maskLayer_2 = CAShapeLayer()
         maskLayer_2.frame = self.bounds
         maskLayer_2.path = maskPath_2.cgPath
          
         self.layer.mask = maskLayer_2
         
     }
    func maskPath_new( size: CGSize)
    {
        let maskPath = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners:[UIRectCorner.topLeft,UIRectCorner.topRight], cornerRadii: size)
       
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }
    //单击的手势
    @objc func clickGesture(target: Any? ,action: Selector?)->UITapGestureRecognizer
    {
        let singleRecognizer = UITapGestureRecognizer.init(target: target, action: action)
        /*单击    -------    点击的次数*/
            singleRecognizer.numberOfTapsRequired = 1
        self.addGestureRecognizer(singleRecognizer)


        return singleRecognizer
    }
    //双击的手势
    @objc func doubleClickGesture(target: Any? , action: Selector?)->UITapGestureRecognizer
    {
        
        let singleRecognizer = UITapGestureRecognizer.init(target: target, action: action)
        /*双击    -------    点击的次数*/
            singleRecognizer.numberOfTapsRequired = 2
        self.addGestureRecognizer(singleRecognizer)
        return singleRecognizer
    }
    

}

extension NSMutableAttributedString {
    
    @objc static func getAttributed(string:String,font:UIFont,foregroundColor:UIColor)-> NSMutableAttributedString {
        
        let attributes = [NSMutableAttributedString.Key.backgroundColor:UIColor.clear,          NSMutableAttributedString.Key.font:font as Any,NSMutableAttributedString.Key.foregroundColor: foregroundColor]
        
        return NSMutableAttributedString.init(string:string as String, attributes: attributes)
        

    }
    //
    @objc func attributes(url:String,font:UIFont ,color:UIColor,link:String)
    {

        let attr35: [NSAttributedString.Key : Any] = [.font: font,.foregroundColor: color,]
        
        let str1:NSString  = self.string as NSString
        let range = str1.range(of: url as String)
     
        self.addAttributes(attr35, range: range)
  
        let attr36: [NSAttributedString.Key : Any] = [.underlineStyle: 1,]
        self.addAttributes(attr36, range: range)

        let attr37: [NSAttributedString.Key : Any] = [.link: link]
        self.addAttributes(attr37, range: range)
        
    }
        
    @objc static func completeStr(_ completeStr:String,splitArray:NSArray)->NSMutableArray
    
    {
        
        //所有表情的位置与内容
        let subStrArray = NSMutableArray()
        for i in 0..<splitArray.count {

            let name = splitArray[i] as! String
            //单位表情的位置与内容
            
            let subStr  =  self.getDuplicateSubStrLocInCompleteStr(completeStr, subStr: name)
            subStrArray.add(subStr)
         
        }
        
        
        
        
        let indexArray  = NSMutableArray()
        for i in 0..<subStrArray.count {

            let dict = subStrArray[i] as! NSDictionary
            
            let index = dict["index"] as! NSNumber
            indexArray.add(index)
          
        }
        
        
        //从小到大排序

        let  sortedArr = self.selectionSort(array: indexArray as! [Int])
        
        let new = NSMutableArray()
        //字典排序

        for i in 0..<sortedArr.count {
        
            let index = sortedArr[i] as NSNumber
            
            for i in 0..<subStrArray.count {
           
                let dict = subStrArray[i] as!NSDictionary
                let index2 = dict["index"] as! NSNumber
               
                if index.intValue == index2.intValue {
                   new.add(dict)
               }
                
            }
             
           
        }
        
        return new
    }
    // MARK: - 快排
    // 输入一个数组，返回从小到大排序的数组

    static func selectionSort(array: [Int]) -> [Int] {
        var sortArray = array
        for i in 0..<sortArray.count {
            var minValueIndex = i
            for j in (minValueIndex + 1)..<sortArray.count {
                if sortArray[minValueIndex] > sortArray[j] { // 得到最小值位置
                    minValueIndex = j
                }
            }
            // 与最小值进行交换
            let temp = sortArray[i]
            sortArray[i] = sortArray[minValueIndex]
            sortArray[minValueIndex] = temp
        }
        return sortArray
    }
    //利用切分先得数组,再根据索引计算
    @objc static func getDuplicateSubStrLocInCompleteStr(_ completeStr:String,subStr:String)->NSMutableArray
   
    {
        
        let separatedStrArr = completeStr.components(separatedBy: subStr)
        let locMuArr = NSMutableArray()
        
        var index:NSInteger = 0
        for i in 0..<separatedStrArr.count-1 {

            let separatedStr = separatedStrArr[i] as String
            index = index + separatedStr.count
           
            let loc_num =  NSNumber.init(value: index)
            
            //表情所在位置与表情
            
            let dict = NSMutableDictionary()
            dict.setObject(loc_num, forKey: "index" as NSCopying)
            dict.setObject(subStr, forKey: "subStr" as NSCopying)

            locMuArr.add(dict)
         
            index = index+subStr.count
        }
        return locMuArr;
    }
    
    
     //111111
     static func getArray()->NSMutableArray
    {
        let array =  ["[hard]","[aha]","[why]","[Fireworks]","[pitiful]","[amaz]","[good]","[cool]","[bye]","[rose]","[slime]","[laugh]","[love]","[tongue]","[daze]","[handclap]","[titter]","[handssors]","[six]","[heart]","[melon]","[silly]","[dog]","[like]","[expect]","[666]","[flower]"]
        
   
        return NSMutableArray.init(array: array)
    }
    static func getExpressionDict()->NSMutableDictionary

    {

//        let array:NSMutableArray = self.getArray()
//        for i in 0..<35 {
//
//            if i>15 {
//                array.add(String.init(format: "[emoticon%i]", i+1))
//            }
//
//
//        }
        
        let expressionDict = NSMutableDictionary()
        expressionDict.setObject("[hard]", forKey: "[fd]" as NSCopying)
        expressionDict.setObject("[aha]", forKey: "[lg]" as NSCopying)
        expressionDict.setObject("[why]", forKey: "[qu]" as NSCopying)
        expressionDict.setObject("[Fireworks]", forKey: "[fl]" as NSCopying)
        expressionDict.setObject("[pitiful]", forKey: "[kl]" as NSCopying)
        expressionDict.setObject("[amaz]", forKey: "[jy]" as NSCopying)
        
        expressionDict.setObject("[good]", forKey: "[[gz]]" as NSCopying)
        expressionDict.setObject("[cool]", forKey: "[hx]" as NSCopying)
        expressionDict.setObject("[love]", forKey: "[tx]" as NSCopying)
        expressionDict.setObject("[bye]", forKey: "[ag]" as NSCopying)
        expressionDict.setObject("rose", forKey: "[S_FLOWER]" as NSCopying)
        
        return expressionDict;
    }
    
    static func getBigExpressionDict()->NSDictionary
    {
        return ["[slime]":"[slime]",
                 "[laugh]":"[laugh]",
                 "[love]":"[love]",
                 "[tongue]":"[tongue]",
                 "[daze]":"[daze]",
                 "[handclap]":"[handclap]",
                 "[titter]":"[titter]",
                 "[handssors]":"[handssors]",
                 "[six]":"[six]",
                 "[heart]":"[heart]",
                 "[melon]":"[melon]",
                 "[silly]":"[silly]",
                 "[dog]":"[dog]",
                 "[like]":"[like]",
                 "[expect]":"[expect]",
                 "[flower]":"[flower]",
                 "[色]":"[emoticon17]",
                 "[调皮]":"[emoticon18]",
                 "[害羞]":"[emoticon19]",
                 "[奸笑]":"[emoticon20]",
                 "[尴尬]":"[emoticon21]",
                 "[惊讶]":"[emoticon22]",
                 "[闭嘴]":"[emoticon23]",
                 "[呲牙]":"[emoticon24]",
                 "[大哭]":"[emoticon25]",
                
                 "[囧]":"[emoticon26]",
                 "[难过]":"[emoticon27]",
                 "[敲打]":"[emoticon28]",
                 "[委屈]":"[emoticon29]",
                 "[疑问]":"[emoticon30]",
                 "[郁闷]":"[emoticon31]",
                 "[再见]":"[emoticon32]",
                 "[可怜]":"[emoticon33]",
                 "[捂脸]":"[emoticon34]",
                 "[笑哭]":"[emoticon35]",
                 "[安慰]":"[emoticon26]",
                 "[666]":"[six]",
    ]
    }
    //生成图文富文本
//    static func getAttributedText(_ str:String,font:UIFont,textColor:UIColor)->NSMutableAttributedString
////    + (NSMutableAttributedString*)getAttributedText:(NSString *)str fontSize:(UIFont*)font foregroundColor:(UIColor*)color
//    {
//
//        let expressionDict = self.getExpressionDict()
//        let expressionDict2 = self.getBigExpressionDict()
//        
//        for i in 0..<expressionDict2.count {
//
//        //  获取字典中所有的key
//            
//            
//         let keys = expressionDict2.allKeys
//        //  取出当前位置对应的key
//         
//         let key = keys[i]
//         let value = expressionDict2[key]
//                     
//            expressionDict.setObject(value as Any, forKey: key as! NSCopying)
//            
////            [expressionDict setObject:value forKey:key];
//
//         }
//        
//        var newStr = str as NSString
//            //将字符串中" name" 全部替换成 expressionDict[name]
//        
//        //例如:找到聊天内容的 "[fd]"换成 @"[hard]"
//        
//        for i in 0..<expressionDict.count {
//            
//            let name = expressionDict[i] as! String
//            newStr = newStr.replacingOccurrences(of:name, with:expressionDict[name] as! String ) as NSString
//
//        }
//        
//       
//        //1.图文混排
//        let String = NSMutableAttributedString()
//        
//        //{
//    //        "index" : 0,
//    //        "subStr" : "[aha]"
//    //    }
//       
//        let subStrArray =  self.completeStr(str, splitArray: self.getArray())
//    
//        let splitter = "(欢拓分割符号)"
//        
//        //占位替换
//        for i in 0..<subStrArray.count {
//         let dict = subStrArray[i] as! NSDictionary
//    
//            //替换 "[aha]" 为 @"(欢拓分割符号)"
//            newStr = newStr.replacingOccurrences(of:dict["subStr"] as! String, with:splitter ) as NSString
//            
//        }
//
//        
//        //分割数据
//        
//        let nameArray = newStr.components(separatedBy: splitter)
//        
//        //找出所有字符串
//        for i in 0..<nameArray.count
//     
//        {
//            
//            let key =  nameArray[i] as String
//           
//            if (key != nil)
//            {
//                
//                
//                //拿到整体的字符串
//                
//                let name = NSMutableAttributedString.init(string: key)
//                
//                // 设置 name 颜色，也可以设置字体大小等
//                
//                [name addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, name.length)];
//                
//                name.addAttributes(range: <#T##NSRange#>)
//                
//                
//                
//                [name addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, name.length)];
//                
//                [String appendAttributedString:name];
//                
//                
//                if (i < subStrArray.count) {
//                    NSDictionary *dict =    subStrArray[i];
//                    
//                    // 创建图片图片附件
//                    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
//                    
//                    NSString*name5 = dict[@"subStr"];
//                    
//                    //替换 "[3]" 为 @"(欢拓分割符号)"
//                    name5 = [name5 stringByReplacingOccurrencesOfString :@"[" withString:@""];
//                    
//                    name5 = [name5 stringByReplacingOccurrencesOfString :@"]" withString:@""];
//                    
//                    
//                    attach.image = [UIImage imageNamed:name5];
//                    attach.bounds = CGRectMake(0, -5 , 22, 22);
//                    
//                    NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
//                    
//                    //将图片插入到合适的位置
//                    [String insertAttributedString:attachString atIndex:String.length];
//                }
//                
//                
//                
//                
//            }
//            
//        }
//        
//        
//        return String;
//        
//    }

}

extension String {
    
    func calculate_the_height(labelWidth:CGFloat,font:UIFont ) ->CGFloat
    {
       
       let label = UILabel.init(frame:CGRect(x: 0, y: 0, width: labelWidth, height: 1.0))
        
        label.font = font;
        label.numberOfLines = 0;
        label.attributedText = NSMutableAttributedString.init(string: self);
        label.lineBreakMode = NSLineBreakMode.byCharWrapping;


        let size = label.sizeThatFits(CGSize(width: label.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
       
        return size.height
    }

}
extension UIImage {
    func getImageWithName(_ named:String) -> UIImage{
        let bundle = Bundle(for: self.classForCoder)
        var image = UIImage(named: "HTLive.bundle/\(named)@2x.png", in: bundle, compatibleWith: nil)
        if image == nil{
            image = UIImage(named: named)
        }
        
        return image!
    }
}
extension UIViewController {
    
    func getCalculateViewFrame(_ isOrientationLandscape:Bool)->CGRect
   
    {
        
        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height
        
        //横屏
        if (isOrientationLandscape) {
            if (width<height) {
                let new_width = UIScreen.main.bounds.size.height
                let new_height =  UIScreen.main.bounds.size.width
                 return CGRect(x: 0, y: 0, width: new_width, height: new_height)
              
            }
           
        }else
        {
            if (width>height) {
                let new_width = UIScreen.main.bounds.size.height
                let new_height =  UIScreen.main.bounds.size.width
                 return CGRect(x: 0, y: 0, width: new_width, height: new_height)
            }
        }
        return CGRect(x: 0, y: 0, width: width, height: height)
       
    }
    
    func TF_dismissUI()
    {
        TalkfunSharedTools.removeFromParentViewController(self, name: "TalkfunScanNewLoginViewController")
        TalkfunSharedTools.removeFromParentViewController(self, name: "TalkfunScanViewController")
        TalkfunSharedTools.removeFromParentViewController(self, name: "TalkfunSecondNewLoginViewController")

         //返回上一页
         if (self.navigationController != nil) {
             self.navigationController?.popViewController(animated: true)

         }else{
             self.dismiss(animated: true)

         }
    }
    
    func TF_alertController(_ msg:String)
    {
        let alert:UIAlertController = UIAlertController.init(title: "温馨提示", message: msg, preferredStyle: .alert)
        let otherAction:UIAlertAction = UIAlertAction.init(title: "确认", style: .default) { action in
            
        }
        alert.addAction(otherAction)
        self.present(alert, animated: true, completion: nil)
    }
    /** 获取当前控制器 */
    static func TF_current() -> UIViewController {
        let keyWindow = TalkfunSharedTools.keyWindow()
        let vc = keyWindow.rootViewController
        return UIViewController.TF_findBest(vc: vc!)
    }
    
    private static func TF_findBest(vc: UIViewController) -> UIViewController {
        if vc.presentedViewController != nil {
            return UIViewController.TF_findBest(vc: vc.presentedViewController!)
        } else if vc.isKind(of: UISplitViewController.self) {
            let svc = vc as! UISplitViewController
            if svc.viewControllers.count > 0 {
                return UIViewController.TF_findBest(vc: svc.viewControllers.last!)
            } else {
                return vc
            }
        } else if vc.isKind(of: UINavigationController.self) {
            let svc = vc as! UINavigationController
            if svc.viewControllers.count > 0 {
                return UIViewController.TF_findBest(vc: svc.topViewController!)
            } else {
                return vc
            }
        } else if vc.isKind(of: UITabBarController.self) {
            let svc = vc as! UITabBarController
            if (svc.viewControllers?.count ?? 0) > 0 {
                return UIViewController.TF_findBest(vc: svc.selectedViewController!)
            } else {
                return vc
            }
        } else {
            return vc
        }
    }
}
